package com.yfbao.horizon.encrypt.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class SHA256Utils {
    private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String EN_CODING = "UTF-8";
    private static MessageDigest digest = null;

    static {
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            log.error("init sha256 digest error", e);
        }
    }

    /**
     * sha256加密
     *
     * @param clearText 明文str
     * @return
     */
    public static String encrypt(String clearText) {
        try {
            return encrypt(clearText.getBytes(EN_CODING));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * sha256 加密
     *
     * @param bytes 明文byte
     * @return
     */
    public static String encrypt(byte[] bytes) {
        return toHexString(encrypt2Byte(bytes));
    }

    /**
     * sha256加密
     *
     * @param bytes 明文byte
     * @return
     */
    public static byte[] encrypt2Byte(byte[] bytes) {
        try {
            synchronized (digest) {
                digest.update(bytes);
                return digest.digest();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHexString(byte[] input){
        String result = "";
        for (int i = 0; i < input.length; i++)
        {
            result += HEX_CHARS[(input[i] >>> 4) & 0x0f];
            result += HEX_CHARS[(input[i]) & 0x0f];
        }
        return result;
    }
}
